package com.cqw.robot.utils;


import lombok.SneakyThrows;
import nu.pattern.OpenCV;
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 小图找大图中的位置
 */
public class FindPicPoint {

    /**
     * 成功获取结果坐标
     * @param args
     */
    public static void main(String[] args) {
        String userDir = System.getProperty("user.dir");
        String targetImg = userDir + "/images/4file.png";
        new FindPicPoint().matchTemplate(targetImg);
    }



    /**
     * 全屏截图
     * @return 返回BufferedImage
     */
    @SneakyThrows
    public static Mat getFullScreenShot() {

        String fileName = File.separator + System.currentTimeMillis() + "file.png";
        int width = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int height = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        Robot robot = new Robot();
        BufferedImage bfImage = robot.createScreenCapture(new Rectangle(0, 0, width, height));
        String userDir = System.getProperty("user.dir");
        ImageIO.write(bfImage, "jpg", new File(userDir + fileName));
        Mat src = Imgcodecs.imread(userDir + fileName);
        Files.delete(Paths.get(userDir + fileName));
        return src;
    }

    /**
     * 大图找小图
     * @param targetImg
     */
    public void matchTemplate(String targetImg) {

        // 1.导入Opencv库
        OpenCV.loadShared();
        // 2.加载图像
        Mat src = getFullScreenShot();
//        Mat src = Imgcodecs.imread(sourceImg);// 待匹配图片
        Mat template = Imgcodecs.imread(targetImg);// 获取匹配模板

        // 3.进行模板匹配
        // 创建一个输出图像
        Mat outputImage = new Mat(src.rows(), src.cols(), src.type());
        Imgproc.matchTemplate(src, template, outputImage, Imgproc.TM_CCOEFF_NORMED);

        // 4.获取匹配结果,查找最大匹配值
        Core.MinMaxLocResult result = Core.minMaxLoc(outputImage);
        Point matchLoc = result.maxLoc;
        double similarity = result.maxVal; //匹配度
        int x = (int) matchLoc.x; //小图大大图中的x坐标
        int y = (int) matchLoc.y; //小图大大图中的y坐标
        System.out.println(x + "," + y + " similarity: " + similarity);

        //将查找到的结果标上框框
        Imgproc.rectangle(src,new Point(x,y),new Point(x+template.cols(),y+template.rows()),
                new Scalar( 0, 0, 255),2);
        //5.显示结果
        HighGui.imshow("模板匹配", src);
        HighGui.waitKey();
    }


}